package giang.ex.andengine;

import java.io.IOException;
import java.util.Random;

import org.anddev.andengine.audio.music.Music;
import org.anddev.andengine.audio.music.MusicFactory;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.ZoomCamera;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.input.touch.detector.ScrollDetector;
import org.anddev.andengine.input.touch.detector.SurfaceScrollDetector;
import org.anddev.andengine.input.touch.detector.ScrollDetector.IScrollDetectorListener;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import org.anddev.andengine.util.MathUtils;

import android.util.DisplayMetrics;
import android.util.Log;

public class SSGardenActivity extends BaseGameActivity implements
		IScrollDetectorListener, IOnSceneTouchListener {
	// ===========================================================
	// Constants
	// ===========================================================
	static final int ORI_WIDTH = 810;
	static final int ORI_HEIGHT = 624;
	static final float MOBILE_RATIO = 0.5f;
	static int[] HOLE_CORD = { 10, 400, 90, 400, 170, 380, 10, 460, 90, 460,
			170, 450, 10, 520, 90, 520, 165, 520, };

	// ===========================================================
	// Fields
	// ===========================================================

	private ZoomCamera mCamera;
	private BitmapTextureAtlas[] mTexture = new BitmapTextureAtlas[5];
	static Plant[] plantList = new Plant[20];
	TextureRegion mHoleTextureRegion;
	TextureRegion mBackgroundTextureRegion;
	SurfaceScrollDetector mScrollDetector;
	TiledTextureRegion mSeed1TextureRegion;
	TiledTextureRegion mFlowerTextureRegion;
	TiledTextureRegion mPlant1TextureRegion;
	private Music mBgMusic;
	SoilSlot[] mySoils = new SoilSlot[9];

	// ===========================================================
	// Constructors
	// ===========================================================

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	public void onLoadComplete() {
		// TODO Auto-generated method stub
	}

	@Override
	public Engine onLoadEngine() {
		final DisplayMetrics displayMetrics = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		float screen_ratio = displayMetrics.widthPixels
				/ (float) displayMetrics.heightPixels;
		float camera_width = ORI_HEIGHT * MOBILE_RATIO * screen_ratio;
		float camera_height = ORI_HEIGHT * MOBILE_RATIO;
		this.mCamera = new ZoomCamera(0, ORI_HEIGHT * (1 - MOBILE_RATIO),
				camera_width, camera_height);
		this.mCamera.setBounds(0, ORI_WIDTH, 0, ORI_HEIGHT);
		this.mCamera.setBoundsEnabled(true);
		return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE,
				new FillResolutionPolicy(), this.mCamera).setNeedsSound(true)
				.setNeedsMusic(true));
	}

	@Override
	public void onLoadResources() {
		for (int i = 0; i < mTexture.length; i++) {
			this.mTexture[i] = new BitmapTextureAtlas(1024, 1024,
					TextureOptions.DEFAULT);
		}

		this.mHoleTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.mTexture[0], this, "gfx/hole.png", 0, 0);
		this.mBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.mTexture[1], this, "gfx/bg.png", 64, 48);
		this.mSeed1TextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createTiledFromAsset(this.mTexture[2], this, "gfx/dua1.png",
						512, 512, 2, 1);
		this.mPlant1TextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createTiledFromAsset(this.mTexture[3], this, "gfx/dua4.png",
						512, 512, 2, 1);

		for (int i = 0; i < mTexture.length; i++) {
			this.mEngine.getTextureManager().loadTexture(this.mTexture[i]);
		}

		MusicFactory.setAssetBasePath("mfx/");
		try {
			this.mBgMusic = MusicFactory.createMusicFromAsset(
					this.mEngine.getMusicManager(), this,
					"theme-srini-7595_hifi.mp3");
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Scene onLoadScene() {
		this.mBgMusic.play();
		this.mEngine.registerUpdateHandler(new FPSLogger());

		final Scene scene = new Scene();
		scene.setOnAreaTouchTraversalFrontToBack();

		this.mScrollDetector = new SurfaceScrollDetector(this);
		this.mScrollDetector.setEnabled(true);

		Sprite background = new Sprite(0, 0, this.mBackgroundTextureRegion);
		// SpriteBackground sb = new SpriteBackground(background);
		// scene.setBackgroundEnabled(true);
		// scene.setBackground(sb);

		// final AnimatedSprite face = new AnimatedSprite(110, 110,
		// this.mFace2TextureRegion);
		// face.animate(1000);
		// scene.attachChild(face);
		// hole.attachChild(face);

		scene.attachChild(background);

		plantList[0] = new Plant(new TiledTextureRegion[] {
				mSeed1TextureRegion, mPlant1TextureRegion });

		for (int i = 0; i < HOLE_CORD.length / 2; i++) {
			mySoils[i] = new SoilSlot(HOLE_CORD[2 * i], HOLE_CORD[2 * i + 1],
					this.mHoleTextureRegion);
			scene.attachChild(mySoils[i]);
			scene.registerTouchArea(mySoils[i]);
		}
		// Sprite[] holes = new Sprite[20];
		// for (int i = 0; i < HOLE_CORD.length / 2; i++) {
		// holes[i] = new Sprite(HOLE_CORD[2 * i], HOLE_CORD[2 * i + 1],
		// this.mHoleTextureRegion) {
		// @Override
		// public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
		// final float pTouchAreaLocalX,
		// final float pTouchAreaLocalY) {
		//
		// // float parentY = ((Sprite)this.getParent()).getHeight();
		// AnimatedSprite plant = new AnimatedSprite(0, 0,
		// SSGardenActivity.this.mSeed1TextureRegion) {
		// @Override
		// public boolean onAreaTouched(
		// final TouchEvent pSceneTouchEvent,
		// final float pTouchAreaLocalX,
		// final float pTouchAreaLocalY) {
		// // this.detachSelf();
		// // plant.
		//
		// return true;
		// }
		// };
		// plant.setPosition(
		// (this.getWidth() - plant.getWidth()) / 2,
		// this.getHeight() / 2
		// - mSeed1TextureRegion.getHeight());
		// plant.animate(1000);
		// // if(this.mChildren.size()==0)
		// this.attachChild(plant);
		// scene.registerTouchArea(plant);
		// return true;
		// }
		// };
		// scene.attachChild(holes[i]);
		// scene.registerTouchArea(holes[i]);
		// }

		scene.setOnSceneTouchListener(this);
		scene.setTouchAreaBindingEnabled(true);
		// scene.registerTouchArea(face);
		growTimeHandler();

		return scene;
	}

	@Override
	public void onScroll(ScrollDetector pScollDetector, TouchEvent pTouchEvent,
			float pDistanceX, float pDistanceY) {
		this.mCamera.offsetCenter(-pDistanceX, -pDistanceY);
	}

	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		this.mScrollDetector.onTouchEvent(pSceneTouchEvent);
		return true;
	}

	// ===========================================================
	// Methods
	// ===========================================================
	private void growTimeHandler() {
		TimerHandler spriteTimerHandler;

				spriteTimerHandler = new TimerHandler(10, new ITimerCallback() {
					@Override
					public void onTimePassed(final TimerHandler pTimerHandler) {
						Random r = new Random(System.currentTimeMillis());
	            	    Log.v("Time Changed", String.valueOf(r.nextInt()));
						for (int i = 0; i < mySoils.length; i++)
							mySoils[i].grow();
					}
				});
				this.getEngine().registerUpdateHandler(spriteTimerHandler);
	}

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
	class SoilSlot extends Sprite {
		private Plant temp;

		public SoilSlot(float pX, float pY, TextureRegion pTextureRegion) {
			super(pX, pY, pTextureRegion);
			// TODO Auto-generated constructor stub
		}

		public void grow() {
			if (this.getChildCount() > 0) {
				
				this.detachChildren();
//				temp = new Plant(new TiledTextureRegion[] {
//						mSeed1TextureRegion, mPlant1TextureRegion });
//				temp.animate(300);
//				temp.setPosition(
//						(this.getWidth() - temp.mSprites[0].getWidth()) / 2,
//						this.getHeight() / 2 - temp.mSprites[0].getHeight());
				this.attachChild(temp.mSprites[1]);
			}

		}

		@Override
		public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
				final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
			// seed(SSGardenActivity.plantList[0]);
			temp = new Plant(new TiledTextureRegion[] { mSeed1TextureRegion,
					mPlant1TextureRegion });
			temp.animate(300);
			temp.setPosition(
					(this.getWidth() - temp.mSprites[0].getWidth()) / 2,
					this.getHeight() / 2 - temp.mSprites[0].getHeight());
			this.attachChild(temp.mSprites[0]);
			return true;
		}

		boolean isAvailable;
		boolean isReady;
		private Sprite mSprite;

		void purchase() {

		}

		void seed(Plant s) {
			this.attachChild(s.mSprites[0]);
		}

		void render() {
		}
	}
}